<?php
include_once "BaseDAO.php";
include_once $_SERVER ['DOCUMENT_ROOT'] . '/ad/sys/com/model/util/plog/classes/plog.php';
include_once $_SERVER ['DOCUMENT_ROOT'] . '/ad/sys/com/model/db/publish/PublishClickedAdDAO.php';
include_once $_SERVER ['DOCUMENT_ROOT'] . '/ad/sys/com/model/db/publish/ClickedAdSumpayDAO.php';
include_once $_SERVER ['DOCUMENT_ROOT'] . '/ad/sys/com/model/db/AppInfoDAO.php';
include_once $_SERVER ['DOCUMENT_ROOT'] . '/ad/sys/com/model/db/PaysettingDAO.php';

class AdDAO extends BaseDAO {
	
	public function __construct() {
		parent::__construct ();
		$this->log = Plog::factory ( __FILE__ );
	}
	
	public function updateAdIsNew() {
		$sql = "
		    update ad set isNew = 0
			where datediff(curdate(), createTime) >=7 
			and isNew = 1 
		";
		mysql_query($sql);
	}
	
	
	
	
	public function updateAdPay($adId,$isPay) {
		$sql = "update ad set IsPay='$isPay' where id=$adId";
		$reuslt =  mysql_query($sql);
		return $reuslt;
	}
	
	public function managerAd($proxyName, $name, $startDate, $endDate, $status, $start , $limit ) {
		$whereSql = "";
		
		if (!is_null($startDate) && $startDate !="") {
			$whereSql.= " and ad.adStartDate >= '$startDate' and ad.adStartDate <= '$endDate'";
			
		}
		
		if (!is_null($proxyName) && $proxyName !="") {
			$whereSql .= " and (select u.name from user u where u.account = user.account)  like '%$proxyName%' ";
		}
		
		if (!is_null($name) && $name != "") {
			$whereSql .= " and user.name  like '%$name%' ";
		}
		
		if (!is_null($status) && $status != "") {
			$whereSql .= " and ad.status = '$status' ";
		}
		
		$sqlCount = "select count(ad.id) from  ad , user where ad.account = user.account $whereSql";
	
		$sql = "
			select
				ad.id, 
			    ad.adName, 
			    ad.status,
			    (select(case count(u.name) when 0 then user.name else u.name end)  from user u where u.account = user.ProxyAccount) as proxyName,
			    user.name,
			    floor((ad.budget / case ad.AdBudgetType when 0 then 1 when 1 then 7 end) * (datediff(ad.adEndDate ,ad.adStartDate)+1)) as sumBudget,
			    ad.actualImpressions,
				ad.actuaClick,
				ad.createTime,
				ad.isPay,
				ad.adStartDate,
				ad.adEndDate,
			    IFNULL((select 
				((select count(id) * (select CPM from paysetting )  from clickedad where status = 0  and adId = a.id)  +
				(select count(id) * (select CPC from paysetting )  from clickedad where status = 1  and adId = a.id ))	
				from clickedad c, ad a 
				where c.adId = a.id and a.account = ad.account and a.id=ad.id limit 1),0)  as point  
			from  ad , user 
			where ad.account = user.account  $whereSql  order by ad.createTime desc limit $start, $limit
		";
		
		$this->log->debug($sql);
		
		
		$count = mysql_fetch_row ( mysql_query($sqlCount) );
		$items = $this->toArray(mysql_query($sql));
		
		return  array("count" => $count[0], "items" =>  $items); 
	}
	
	public function updateAd($adId, $status, $description, $adName) {
		$sql = "update ad set status='$status', description ='$description' where id='$adId'";
		$reuslt =  mysql_query($sql);
		
		$statusText = "";
		switch($status) {

			case "1" : $statusText = "審核完成"; break;
			case "2" : $statusText = "結束"; break;
			case "3" : $statusText = "暫停"; break;
			case "4" : $statusText = "刪除"; break;
			case "5" : $statusText = "未通過"; break;
			case "6" : $statusText = "需修改"; break;
			
			 
		}
		if ($status != "0") { 
			$notyfySql = "INSERT INTO adnotify (adId,content) values($adId, '<em><a href=/ad/sys/com/control/AdService.php?action=tigetStep1Action&adId=$adId> $adName </a></em>廣告已 $statusText 。');";
			mysql_query($notyfySql);
		}
		return $reuslt;
	}
	
	public function getAdById($adId) {
		$sql = "select * from ad where id='$adId'";
		return @mysql_fetch_object(@mysql_query($sql));
	}
	
	public function getAdByAccount($account) {
		$sql = "select * from ad where account='$account'";
		return $this->toArray ( @mysql_query ( $sql ) );
	}
	public function getAd($id) {
		$sql = "select * from ad where id='$id'";
//		echo "$sql<br/>";
		return $this->toArray ( @mysql_query ( $sql ) );
	}
	
	public function getAdToArray($id) {
		$sql = "select * from ad where id='$id'";
//		echo "$sql<br/>";
		$result =  @mysql_query($sql);
		return 	mysql_fetch_array($result);
	}
	
	
	public function getAdReportByAcount($account,$start, $limit) {
		$temp = mysql_query("select count(*) from ad where account = '$account'");
		$count = mysql_fetch_row($temp) ;
		 
		
		$sql = "select Id,AdName,AdStartDate,AdEndDate,Status,
				floor((budget / case AdBudgetType when 0 then 1 when 1 then 7 end) * (datediff(adEndDate ,adStartDate)+1)) as Budget
				from ad where account ='$account' order by createtime desc limit $start,$limit";
		 
		$result = @mysql_query($sql) or die(@mysql_error());
		$items =  $this->toArray($result);
		 
		return  array("count" => $count[0], "items" =>  $items); 
	}
	
	/**
	 * 取得管理報表
	 * Enter description here ...
	 * @param unknown_type $account
	 * @param unknown_type $adStringDate
	 * @param unknown_type $adEndDate
	 * @param unknown_type $adBillingType
	 */
	public function getManagerReport($account, $id, $adStartDate, $adEndDate, $adBudgetType) {
		$sql = "select 
					 AdName,
				     AdStartDate,
				     AdEndDate,
				     Id,
				     ActualImpressions,
				     ActuaClick,
				     IFNULL(ClickRate, 0) ClickRate,
					 IFNULL((select 
							((select count(id) * (select CPM from paysetting )  from clickedad where status = 0  and adId = a.id)  +
							(select count(id) * (select CPC from paysetting )  from clickedad where status = 1  and adId = a.id ))	
							from clickedad c, ad a 
							where c.adId = a.id and a.account = ad.account and a.id=ad.id limit 1),0)  as point  
				  from ad  where account='$account'
				  and adStartDate >= '$adStartDate' and adStartDate <= '$adEndDate' and adBudgetType='$adBudgetType' ";
		
		if ($id != "all") {
			$sql .= " and id='$id'";
		}
	
		$result = @mysql_query ( $sql ) or die ( @mysql_error () );
		$items = $this->toArray ( $result );
		
		return $items;
	}
	
	public function queryAdByCreatetimeAndStatus($start, $limit, $account, $whereDate, $whereStatus) {
		$whereSQL = " where account='$account' ";
		switch ($whereDate) {
			case "1" :
				$whereSQL .= " and date_format(createTime,'%Y/%m/%d')  
						     between  date_add(date_format(now(),'%y/%m/%d'), interval -1 week)
						     and date_format(now(),'%Y/%m/%d') ";
				break;
			case "2" :
				$whereSQL .= " and date_format(createTime,'%Y/%m/%d')  
						     between  date_add(date_format(now(),'%y/%m/%d'), interval -1 month)
						     and date_format(now(),'%Y/%m/%d')";
				break;
		}
		
		switch ($whereStatus) {
			case "1" :
			case "2" :
			case "3" :
				$whereSQL .= " and status = $whereStatus ";
				break;
			case "4" :
				$whereSQL .= " and status <> $whereStatus ";
				break;
		}
		
		$temp = mysql_query ( "select count(*) from ad $whereSQL" ) or die ( $this->log->error ( mysql_error () ) );
		$count = mysql_fetch_row ( $temp );
		
		if ($count [0] > 0) {
			$sql = "select 
						AdName,
						Status,
						AdStartDate,
						AdEndDate,
						floor((budget / case AdBudgetType when 0 then 1 when 1 then 7 end) * (datediff(adEndDate ,adStartDate)+1)) as Budget ,
						IFNULL((select 
						((select count(id) * (select CPM from paysetting )  from clickedad where status = 0  and adId = a.id)  +
						(select count(id) * (select CPC from paysetting )  from clickedad where status = 1  and adId = a.id ))	
						from clickedad c, ad a 
						where c.adId = a.id and a.account = ad.account and a.id=ad.id limit 1),0)  as  Outlay
					from ad  
					$whereSQL order by createtime desc limit $start,$limit";
			
			$result = mysql_query ( $sql ) or die ( $this->log->error ( mysql_error () ) );
			$item = $this->toArray ( $result );
		} else {
			$item = array ();
		}
		
		return array ("count" => $count [0], "item" => $item );
	}
	
	public function menagerAd($account) {
		
		$result = array ();
		
		//$adSQL = "select * from ad where account='$account'  order by createtime desc";
		/*
		 * 

		 * 
		 */

		$adNotify = "
			select n.* from ad a,adnotify n where  
			a.account='$account' and a.id=n.adId 
			order by n.createtime desc
		";
		
		$adPay = "
			select 
				date_format(c.createTime, '%Y/%m/%d') createtime,
			    (
			      SELECT sum((
		              CASE status  
		                  WHEN 1 THEN  (select CPM from paysetting)
		                  WHEN 0 THEN  (select CPC from paysetting)  
		              END))
		          FROM  clickedad 
		          where  date_format(CreateTime, '%Y/%m/%d') = date_format(c.CreateTime, '%Y/%m/%d') and adid =a.id
		        ) as pay  
			from clickedad c, ad a 
			where c.adId = a.id and a.account = '$account'  
			group by date_format(c.createTime, '%Y/%m/%d') 
			order by createTime desc					
		";
		
		//$ad  = $this->toArray(mysql_query($adSQL)) ;
		

		//$result["ad"] = $ad; //查詢上版廣告
		$result ["pay"] = $this->toArray ( mysql_query ( $adPay ) ); //查詢 付款紀錄
		$result ["notify"] = $this->toArray ( mysql_query ( $adNotify ) ); //查詢通知紀錄
		

		return $result;
	}
	
	/**
	 * 查詢帳號 下的 帳單管理
	 * Enter description here ...
	 * @param unknown_type $account
	 */
	public function getAccountSettle($start, $limit, $account) {
		$sql = "select count(id) from ad where account='$account'";
		$count = mysql_fetch_row ( mysql_query ( $sql ) );
		
		$sql = "
			select date_format(createTime,'%Y/%m/%d') as createtime,
	        adname,
	        id,
		    floor((budget / case AdBudgetType when 0 then 1 when 1 then 7 end) * (datediff(adEndDate ,adStartDate)+1)) as sumBudget,
	        description
			from ad
			where account = '$account' 
			order by createtime desc  limit $start,$limit
		";
		$reuslt = mysql_query ( $sql ) or die ( mysql_error () );
		$item = $this->toArray ( $reuslt );
		
		return array ("count" => $count [0], "item" => $item );
	}
	public function modifyAd($ad) { 
		$sql = "delete from adcategorset where adId=$ad->adId ";
		@mysql_query ( $sql ) or die ( mysql_error () );
		
        $category = $ad->category;
			
	    $categorySql = "INSERT INTO adcategorset values";
			
		foreach ( $category as $value ) {
			$categorySql .= "($ad->adId,'$value'),";
		}
		
		$categorySql = substr ( $categorySql, 0, strlen ( $categorySql ) - 1 );
		 
		mysql_query ( $categorySql ) or die ( mysql_error () );
		
		$sql = "
			update ad set Url='$ad->url',Title='$ad->title',Image1='$ad->image1',Image2='$ad->image2',
			Area='$ad->area',AreaName='$ad->areaName', AgeStart='$ad->ageStart', AgeEnd='$ad->ageEnd' ,Sex= '$ad->sex' ,
			AdName='$ad->adName',AdBudgetType='$ad->adBudgetType',AdStartDate='$ad->adStartDate', AdEndDate='$ad->adEndDate',
			AdBillingType=	'$ad->adBillingType',ClickAction='$ad->clickAction', Budget=$ad->budget where id=$ad->adId
		";
		
		$result = @mysql_query ( $sql ) or die ( mysql_error () );
		return $result;
	}
	
	public function newAd($ad) {
		try {
			$sql = "INSERT INTO `ad` (
				   `Account`, `Url`, `Title`, `Image1`, `Image2`,
				   `Area`,`AreaName`, `AgeStart`, `AgeEnd`, `Sex`, `AdName`, 
				   `AdBudgetType`,`AdStartDate`, `AdEndDate`, `AdBillingType`,ClickAction, Budget) 
				    VALUES (
					  '$ad->account', '$ad->url', '$ad->title', '$ad->image1', '$ad->image2',
					  '$ad->area','$ad->areaName','$ad->ageStart', '$ad->ageEnd', '$ad->sex','$ad->adName',
					  '$ad->adBudgetType','$ad->adStartDate','$ad->adEndDate','$ad->adBillingType','$ad->clickAction',
				       $ad->budget	
					 );";
			
			$this->log->debug ( "新增廣告:" . $sql );
			
			$result = @mysql_query ( $sql ) or die ( mysql_error () );
			$adId = @mysql_insert_id ();
			
			$this->log->debug ( "新增廣告筆數:" . $result );
			//新增廣告類別
			

			$category = $ad->category;
			
			$categorySql = "INSERT INTO adcategorset values";
			
			foreach ( $category as $value ) {
				$categorySql .= "($adId,'$value'),";
			}
			
			$categorySql = substr ( $categorySql, 0, strlen ( $categorySql ) - 1 );
			$notyfySql = "INSERT INTO adnotify (adId,content) values($adId, '<em> <a href=/ad/sys/com/control/AdService.php?action=tigetStep1Action&adId=$adId>$ad->adName</a> </em>廣告已完成建立。');";
			
			mysql_query ( $categorySql ) or die ( mysql_error () );
			
			mysql_query ( $notyfySql ) or die ( mysql_error () );
			return array ("count" => $result, "adId" => $adId );
		} catch ( Exception $e ) {
			mysql_error ();
			throw $e;
		}
	
	}
	
	//		select sex,AgeStart,AgeEnd from ad
	//--性別
	//where (sex=0 or sex=1)
	//--年齡層
	//and 5 between AgeStart and AgeEnd
	//--刊登日期
	//and now() between AdStartDate and AdEndDate 
	//--廣告狀態 1.刊登中
	//and Status=1
	//使用期限
	//and (lifetime is null or Lifetime>=now())
	//還有預算
	//	and ((Overage > CPM and AdBillingType='CPM') or (Overage > CPC and AdBillingType='CPC'))
	//沒有超過今天Quota
	//  and ((AdBudgetType=1 and Budget>0) or (AdBudgetType=2 and Budget/7>0)  or (AdBudgetType=3 and Budget/30>0) )
	public function queryAd($md5key, $imei) {
		$paysettingDAO=new PaysettingDAO();
		$paysettingArray=$paysettingDAO->getInfo();
		$paysetting=$paysettingArray[0];
		$CPC=$paysetting->CPC;
		$CPM=$paysetting->CPM;
		$CPMPublish=$paysetting->CPMPublish;
		$CPCPublish=$paysetting->CPCPublish;
		try {
			$sql = " 
			select count(*) from ad join user on ad.Account=user.account 
			where date_format(now(),'%Y/%m/%d') between ad.AdStartDate
				  and ad.AdEndDate and ad.Status=1 
				  and ((user.count > $CPM and ad.AdBillingType='CPM') 
				  		 and ((floor(Budget/$CPM)> (SELECT count(*) FROM `clickedad` where AdId=ad.id and date_format(CreateTime, '%Y/%m/%d')= date_format(now(),'%Y/%m/%d') and status=0) and AdBudgetType=0 )
				  		 or (floor(Budget/7/$CPM)> (SELECT count(*) FROM `clickedad` where AdId=ad.id and date_format(CreateTime, '%Y/%m/%d')= date_format(now(),'%Y/%m/%d') and status=0) and AdBudgetType=1 ))  
			             or(user.count > $CPC and ad.AdBillingType='CPC') 
			             and ((floor(Budget/$CPC)>(SELECT count(*) FROM `clickedad` where AdId=ad.id and date_format(CreateTime, '%Y/%m/%d')=date_format(now(),'%Y/%m/%d') and status =1 ) and AdBudgetType=0 )
			             or (floor(Budget/7/$CPM) >(SELECT count(*) FROM `clickedad` where AdId=ad.id and date_format(CreateTime, '%Y/%m/%d')=date_format(now(),'%Y/%m/%d') and status =1 ) and AdBudgetType=1 )) 
			             
			          )
								 		
					";
			
			//echo $sql;
			$temp = @mysql_query ( $sql ) or die ( mysql_error () );
			$count = mysql_fetch_row ( $temp );
			//如果筆數大於0 傳回隨機一筆
			if ($count [0] > 0) {
				$appInfoDAO = new AppInfoDAO ();
				$appInfoArray = $appInfoDAO->getAppInfoDetailByMd5key ( $md5key );
				
				$appInfo = $appInfoArray [0];
				$appId=$appInfo->id;
				$rand = rand ( 0, $count [0]-1 );
				$sql = " 
			select ad.* from ad join user on ad.Account=user.account 
			where date_format(now(),'%Y/%m/%d') between ad.AdStartDate
				  and ad.AdEndDate and ad.Status=1 
				  and ((user.count > $CPM and ad.AdBillingType='CPM') 
				  		 and ((floor(Budget/$CPM)> (SELECT count(*) FROM `clickedad` where AdId=ad.id and date_format(CreateTime, '%Y/%m/%d')= date_format(now(),'%Y/%m/%d') and status=0) and AdBudgetType=0 )
				  		 or (floor(Budget/7/$CPM)> (SELECT count(*) FROM `clickedad` where AdId=ad.id and date_format(CreateTime, '%Y/%m/%d')= date_format(now(),'%Y/%m/%d') and status=0) and AdBudgetType=1 ))  
			             or(user.count > $CPC and ad.AdBillingType='CPC') 
			             and ((floor(Budget/$CPC)>(SELECT count(*) FROM `clickedad` where AdId=ad.id and date_format(CreateTime, '%Y/%m/%d')=date_format(now(),'%Y/%m/%d') and status =1 ) and AdBudgetType=0 )
			             or (floor(Budget/7/$CPC) >(SELECT count(*) FROM `clickedad` where AdId=ad.id and date_format(CreateTime, '%Y/%m/%d')=date_format(now(),'%Y/%m/%d') and status =1 ) and AdBudgetType=1 )) 
			             
			          )
																	limit $rand,1
				    ";
				$result = @mysql_query ( $sql ) or die ( mysql_error () );
				$items = $this->toArray ( $result );
				if('4'==$appInfo->status)
				{
				//echo "items[0]->Id---->".$items[0]->Id."<br/>";
				$this->upateAdEstimateImpressions ( $items [0]->Id );
				$this->upateAdImpressionsRate ( $items [0]->Id );
				if($items [0]->AdBillingType == 'CPM')
				{
					$this->upateAdOverageAndOutlay ( $items [0]->Account );
				}
				//echo "$appId<br/>";
				$this->insertPre ( $items [0]->Id, $imei, $appId, ($items [0]->AdBillingType == 'CPM') ? 0 : $CPMPublish );
				//echo "<br>appInfo->Account=".$appInfo->Account."<br>";
				$this->procClickedAdSumpay ( $appId, $appInfo->account, ($items [0]->AdBillingType == 'CPM') ? 0 : $CPMPublish );
				}
				return array ("item" => $items, "appInfo" => $appInfo );
			} else {
				//echo "not find data=>sql=$sql";
				$item = array ();
			}
			
			return array ("item" => $item );
		} catch ( Exception $e ) {
			mysql_error ();
			throw $e;
		}
	}
	public function clickAd($md5Key, $imei, $adid) {
		$paysettingDAO=new PaysettingDAO();
		$paysettingArray=$paysettingDAO->getInfo();
		$paysetting=$paysettingArray[0];
		$CPC=$paysetting->CPC;
		$CPM=$paysetting->CPM;
		$CPMPublish=$paysetting->CPMPublish;
		$CPCPublish=$paysetting->CPCPublish;
		$appInfoDAO = new AppInfoDAO ();
		$appInfoArray = $appInfoDAO->getAppInfoByMd5key($md5Key );
		$appInfo = $appInfoArray [0];
		$appId=$appInfo->id;
		$adArray = $this->getAd ( $adid );
		@$ad = $adArray [0];
		//echo $this->clickOk($adid,$CPC)."<br/>";
		if(!$this->clickOk($adid,$CPC))
		{
			return "{failure:overrun}";
		}
		if('4'==$appInfo->status)
		{
		
		$this->upateAdEstimateClick ( $adid );
		$this->upateAdClickRate ( $adid );
		if($ad->AdBillingType == 'CPC')
		{
			$this->upateAdOverageAndOutlayClick ( $ad->Account );
		}
		$this->insertClick ( $ad->Id, $imei, $appId, ($ad->AdBillingType == 'CPC') ?  $CPCPublish:0  );
		//echo "<br>appInfo->Account=".$appInfo->Account."<br>";
		$this->procClickedAdSumpay ( $appId, $appInfo->account, ($ad->AdBillingType == 'CPC') ?  $ad->CPCPublish:0  );
		}
		return "{success:true}";
		}
	private function clickOk($adid,$CPC)
	{
		try {
			$sql = "
		SELECT COUNT( * ) 
		FROM ad
		WHERE id =$adid
		AND (
		(
		(
		floor(Budget /$CPC)
		) > ( 
		SELECT COUNT( * ) 
		FROM  `clickedad` 
		WHERE AdId =$adid and status=1
		AND DATE_FORMAT( CreateTime,  '%Y/%m/%d' ) = DATE_FORMAT( NOW( ) ,  '%Y/%m/%d' ) ) 
		AND AdBudgetType =0
		)
		OR (
		(
		floor(Budget /7 /$CPC)
		) > ( 
		SELECT COUNT( * ) 
		FROM  `clickedad` 
		WHERE AdId =$adid and status=1
		AND DATE_FORMAT( CreateTime,  '%Y/%m/%d' ) = DATE_FORMAT( NOW( ) ,  '%Y/%m/%d' ) ) 
		AND AdBudgetType =1
		)
		AND STATUS =1
		)			
				    ";
			//echo $sql."<br/>";
		$result = mysql_query ( $sql ) or die ( mysql_error () );
		$count = mysql_fetch_row($result);
		return $count[0]>0;
		//$item = $this->toArray ( $reuslt );
		
		} catch ( Exception $e ) {
			mysql_error ();
			throw $e;
		}
	}
	private function upateAdEstimateImpressions($id) {
		//echo $id . "<br/>";
		try {
			$sql = " update ad 
					set ActualImpressions=ActualImpressions+1
					where id=$id 
				    ";
			//echo $sql."<br/>";
			$result = @mysql_query ( $sql ) or die ( mysql_error () );
		} catch ( Exception $e ) {
			mysql_error ();
			throw $e;
		}
	}
	private function upateAdEstimateClick($id) {
		//echo $id . "<br/>";
		try {
			$sql = " update ad 
					set ActuaClick=ActuaClick+1
					where id=$id 
				    ";
			//echo $sql."<br/>";
			$result = @mysql_query ( $sql ) or die ( mysql_error () );
		} catch ( Exception $e ) {
					echo "$e<br/>";
			
			mysql_error ();
			throw $e;
		}
	}
	private function upateAdOverageAndOutlay($id) {
		$paysettingDAO=new PaysettingDAO();
		$paysettingArray=$paysettingDAO->getInfo();
		$paysetting=$paysettingArray[0];
		$CPC=$paysetting->CPC;
		$CPM=$paysetting->CPM;
		$CPMPublish=$paysetting->CPMPublish;
		$CPCPublish=$paysetting->CPCPublish;
		//echo $id."<br/>";
		try {
			$sql = " update user 
					set count=count-$CPM
					where account='$id' 
				    ";
			//echo $sql;
			$result = @mysql_query ( $sql ) or die ( mysql_error () );
		} catch ( Exception $e ) {
			mysql_error ();
			throw $e;
		}
	}
	private function upateAdOverageAndOutlayClick($id) {
		$paysettingDAO=new PaysettingDAO();
		$paysettingArray=$paysettingDAO->getInfo();
		$paysetting=$paysettingArray[0];
		$CPC=$paysetting->CPC;
		$CPM=$paysetting->CPM;
		$CPMPublish=$paysetting->CPMPublish;
		$CPCPublish=$paysetting->CPCPublish;
		//echo $id."<br/>";
		try {
			$sql = " update user 
					set count=count-$CPC
					where account='$id' 
				    ";
			//echo $sql;
			$result = @mysql_query ( $sql ) or die ( mysql_error () );
		} catch ( Exception $e ) {
			mysql_error ();
			throw $e;
		}
	}
	private function upateAdImpressionsRate($id) {
		//echo $id."<br/>";
		try {
			$sql = " update ad 
					set ImpressionsRate=ActualImpressions/EstimateImpressions
					where id=$id
				    ";
			//echo $sql;
			$result = @mysql_query ( $sql ) or die ( mysql_error () );
		} catch ( Exception $e ) {
			mysql_error ();
			throw $e;
		}
	}
	private function upateAdClickRate($id) {
		//echo $id."<br/>";
		try {
			$sql = " update ad 
					set ClickRate=ActuaClick/EstimateClick
					where id=$id
				    ";
			//echo $sql;
			$result = @mysql_query ( $sql ) or die ( mysql_error () );
		} catch ( Exception $e ) {
			mysql_error ();
			throw $e;
		}
	}
	private function insertPre($adid, $IMEI, $APPID, $PayMoney) {
		try {
			@session_start ();
			@$user = Util::jsonToObject ( $_SESSION ["user"] );
			
			$nowDate = Util::getNowDate ();
			$param = array ("Action" => 1, "AdId" => $adid, "IMEI" => $IMEI, "APPID" => $APPID, "PayMoney" => $PayMoney, "status" => 0, "CreateTime" => $nowDate );
			
			$publishClickedAdDAO = new PublishClickedAdDAO ();
			$reuslt = $publishClickedAdDAO->insertData ( $param );
		
		} catch ( Exception $e ) {
			echo $e->getMessage ();
		}
	}
	private function insertClick($adid, $IMEI, $APPID, $PayMoney) {
		try {
			@session_start ();
			@$user = Util::jsonToObject ( $_SESSION ["user"] );
			
			$nowDate = Util::getNowDate ();
			$param = array ("Action" => 1, "AdId" => $adid, "IMEI" => $IMEI, "APPID" => $APPID, "PayMoney" => $PayMoney, "status" => 1, "CreateTime" => $nowDate );
			
			$publishClickedAdDAO = new PublishClickedAdDAO ();
			$reuslt = $publishClickedAdDAO->insertData ( $param );
		
		} catch ( Exception $e ) {
			echo $e->getMessage ();
		}
	}
	private function procClickedAdSumpay($appId, $account, $PayMoney) {
		//echo "appId=$appId, account=$account, $PayMoney=PayMoney";
		try {
			$clickedAdSumpayDAO = new ClickedAdSumpayDAO ();
			if (0 == $clickedAdSumpayDAO->cnt ( $appId, $account )) {
				$clickedAdSumpayDAO->insertPojo ( $appId, $account );
			}
			$clickedAdSumpayDAO->addMoney ( $appId, $account, $PayMoney );
		
		} catch ( Exception $e ) {
			echo $e->getMessage ();
		}
	}

}

?>